package main

import (
	"context"
	"google.golang.org/grpc/credentials"
	"grpc-example/data"
	"log"
	"os"
	"time"

	"google.golang.org/grpc"
	pb "grpc-example/protobuf/helloworld"
)

/*
1）首先使用 grpc.Dial() 与 gRPC 服务器建立连接；
2）使用pb.NewGreeterClient(conn)获取客户端；
3）通过客户端调用ServiceAPI方法client.SayHello
*/
const (
	address     = "localhost:50051"
	defaultName = "world"
)

func main() {
	// 客户端通过ca证书来验证服务的提供的证书
	creds, err := credentials.NewClientTLSFromFile(data.Path("x509/ca.crt"), "www.chauncy.com")
	// 1.与server建立连接
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	//conn, err := grpc.DialContext(ctx, address, grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithBlock())
	conn, err := grpc.DialContext(ctx, address, grpc.WithTransportCredentials(creds), grpc.WithBlock())
	//conn, err := grpc.Dial(address, grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithBlock())
	//conn, err := grpc.Dial(address, grpc.WithTransportCredentials(creds), grpc.WithBlock())
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()
	// 2.获取客户端
	c := pb.NewGreeterClient(conn)

	// 通过命令行参数指定 name
	name := defaultName
	if len(os.Args) > 1 {
		name = os.Args[1]
	}
	defer cancel()
	// 客户端调用
	r, err := c.SayHello(ctx, &pb.HelloRequest{Name: name})
	if err != nil {
		log.Fatalf("could not greet: %v", err)
	}
	log.Printf("Greeting: %s", r.GetMessage())
}
